import React, { useMemo } from 'react';
import { CenterPanelProps } from '../../types';
import LoadingSpinner from '../LoadingSpinner';
import EditableText from '../EditableText';
import MarkdownRenderer from '../MarkdownRenderer';
import PastTurn from './PastTurn';

const CenterPanel: React.FC<CenterPanelProps> = ({
  isImageLoading,
  currentAiTask,
  currentImage,
  currentTurn,
  gameHistory,
  isLoading,
  customAction,
  defaultImageModelExists,
  mainContentRef,
  setCustomAction,
  handleOptionClick,
  handleCustomActionSubmit,
  updateField,
}) => {

  const currentTurnIndex = gameHistory.length - 1;

  const memoizedPastTurns = useMemo(() => {
    return gameHistory.slice(0, -1).map((turn, index) => (
      <PastTurn key={turn.id} turn={turn} index={index} />
    ));
  }, [gameHistory]);

  const loadingText = currentAiTask || (gameHistory.length === 0 ? "加载初始游戏状态..." : "AI 处理中...");

  return (
    <div className="bg-gray-800 rounded-lg shadow-md flex-grow flex flex-col overflow-hidden p-3 sm:p-4 h-full">
      {defaultImageModelExists && (
        <div className="relative flex-shrink-0 mb-3 sm:mb-4 h-48 sm:h-64 md:h-80 bg-gray-700 rounded-md overflow-hidden flex items-center justify-center group">
          {isImageLoading ? <LoadingSpinner text={currentAiTask || "图片加载中..."} /> :
            currentImage ? <img src={currentImage} alt={currentTurn?.imageQuery || "游戏场景"} className="w-full h-full object-cover" /> :
            <div className="text-gray-500 p-4 text-center">{currentTurn?.imageQuery ? "加载图片或无图片信息" : "无图片提示"}</div>}
        </div>
      )}

      <div ref={mainContentRef} className="flex-grow overflow-y-auto mb-3 sm:mb-4 pr-1 text-sm sm:text-base leading-relaxed flex flex-col">
        <div className="flex-grow">
          {memoizedPastTurns}
          {gameHistory.length === 1 && gameHistory[0].narrative && <div className="flex-grow"></div>} {/* Spacer for first turn narrative */}
        </div>
        {currentTurn && (<div className="mt-auto pt-2 border-t border-gray-700"><p className="text-gray-400 text-xs mb-1">当前回合: {gameHistory.length}</p><EditableText isTextArea initialValue={currentTurn.narrative} onSave={(newVal) => updateField(`gameHistory.${currentTurnIndex}.narrative`, newVal)} textClassName="text-gray-100" inputClassName="bg-gray-700 text-gray-100 p-2 rounded w-full min-h-[100px]" disabled={isLoading}>
          <MarkdownRenderer content={currentTurn.narrative || (isLoading ? 'AI 正在书写...' : '')} />
        </EditableText></div>)}
      </div>

      {isLoading ? (<div className="flex-shrink-0 py-4 flex flex-col items-center justify-center"><LoadingSpinner text={loadingText} /></div>
      ) : (currentTurn && (
        <div className="flex-shrink-0 space-y-2 sm:space-y-3" data-guide-id="player-action-area">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 sm:gap-3">
            {currentTurn.options.map((option, index) => (<button key={index} onClick={() => handleOptionClick(option, index)} disabled={isLoading} className="w-full p-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md shadow hover:shadow-lg disabled:opacity-60 text-sm break-words"><EditableText initialValue={option} onSave={(newVal) => updateField(`gameHistory.${currentTurnIndex}.options.${index}`, newVal)} textClassName="text-center" inputClassName="bg-blue-800 text-white p-1 rounded w-full text-center" disabled={isLoading} /></button>))}
          </div>
          <div className="flex items-center gap-2">
            <input type="text" value={customAction} onChange={(e) => setCustomAction(e.target.value)} placeholder="或输入自定义行动..." disabled={isLoading} className="flex-grow p-2 bg-gray-700 border border-gray-600 rounded-md shadow-sm focus:ring-blue-500 outline-none text-sm" onKeyPress={(e) => e.key === 'Enter' && handleCustomActionSubmit()} />
            <button onClick={handleCustomActionSubmit} disabled={isLoading || !customAction.trim()} className="p-2 bg-green-600 hover:bg-green-700 text-white rounded-md shadow disabled:opacity-60 text-sm">提交</button>
          </div>
        </div>))}
    </div>
  );
};

export default CenterPanel;
